package com.vedu.interceptor;

import com.diandian.constant.PlatformErrorMsg;
import com.diandian.exception.MyRunTimeException;
import com.diandian.result.Result;
import com.vedu.helper.MessageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * version: $Id: $
 *
 * @author yuancheng.li [create on 2017-12-16]
 */
@ControllerAdvice
public class ExceptionHandle {

    @Autowired
    private MessageHelper messageHelper;

    private static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result handleException(Exception e) {

        logger.error(e.getMessage());

        Result errorResult = new Result();
        String code = null;
        String errorMsg = null;
        if (e instanceof MyRunTimeException) {
            MyRunTimeException myRuntimeException = (MyRunTimeException) e;
            code = myRuntimeException.getCode();
            errorMsg = myRuntimeException.getMsg();
        } else {
            code = PlatformErrorMsg.SYSTEM_ERROR;
            errorMsg = PlatformErrorMsg.SYSTEM_ERROR_MSG;
        }
        errorResult.setCode(code);
        errorResult.setMsg(errorMsg);

        return messageHelper.resolveResultMsg(errorResult);
    }

}
